<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\user;

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

class EmailMessageService
{
    /**
     * 邮件发送
     * @param  string $to 收件方
     * @param  string $title 标题
     * @param  string $content 内容
     * @return bool 返回结果
     */
    public static function send($to, $title, $content)
    {
        $emailConfig = config('site.email');
        $from        = $emailConfig['from'];
        $password    = $emailConfig['password'];
        $smtp        = $emailConfig['smtp'];
        $port        = $emailConfig['port'];

        // 根据端口判断是否使用SSL
        $protocol = ($port == 465) ? 'smtps' : 'smtp';

        // 构建DSN，对于465端口使用smtps协议
        $dsn = sprintf('%s://%s:%s@%s:%s', $protocol, urlencode($from), urlencode($password), $smtp, $port);

        try {
            $transport = Transport::fromDsn($dsn);
            $mailer    = new Mailer($transport);
            $email     = (new Email())
                ->from($from)
                ->to($to)
                ->subject($title)
                ->text(strip_tags($content))
                ->html($content);

            $mailer->send($email);
            return true;
        } catch (\Exception $e) {
            // 记录详细错误日志
            error_log('邮件发送失败 - DSN: ' . $dsn . ' - 错误: ' . $e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }

}